package com.mojo.concurrent.concurrent_05_util;

import javax.swing.*;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * 信号标应用
 *
 * @author <a href="mailto:mojo_jj@163.com">Mojo</a>
 */
public class SemaphoreDemo02 {
    // 1、创建线程池
    static int poolSize = 30;
    static ExecutorService executor = Executors.newFixedThreadPool(poolSize);

    public static void main(String[] args) {
        // 定义信号量的permits大小，
        Semaphore semaphore = new Semaphore(10);
        for (int i = 0; i < poolSize; i++) {
            executor.execute(new SemaphoreTask(semaphore));
        }
        executor.shutdown();
    }
}

//创建信号量任务
class SemaphoreTask implements Runnable {
    Semaphore semaphore;

    public SemaphoreTask(Semaphore semaphore) {
        this.semaphore = semaphore;
    }

    @Override
    public void run() {
        try {
            // 获取锁
            semaphore.acquireUninterruptibly();
            System.out.println(Thread.currentThread().getName() + "，可用信号量：" + semaphore.availablePermits());
            Thread.sleep(2000L);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            semaphore.release();
        }

    }
}